package com.wh.base.sys.offer.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.base.aop.documented.OperLog;
import com.wh.base.sys.cert.entity.Cert;
import com.wh.base.sys.offer.controller.form.*;
import com.wh.base.sys.offer.entity.Offer;
import com.wh.base.sys.offer.service.OfferService;
import com.wh.base.sys.other.entity.Other;
import com.wh.base.sys.user.service.UserService;
import com.wh.base.util.ExcelUtil;
import com.wh.base.util.R;
import com.wh.base.util.RedisUtil;
import com.wh.base.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author Pny
 * @Date 2022/5/20
 */
@Controller
@RequestMapping("/sys/offer")
public class OfferController {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

    @Resource
    private OfferService offerService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Resource
    private ExcelUtil excelUtil;

    @GetMapping("/index")
    @ApiOperation(value = "首页页面")
    @SaCheckPermission("offer:view")
    public String index(Model model){
        model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+ StpUtil.getLoginIdAsLong())); //用户权限
        return "offer/index";
    }

    @PostMapping("/getPage")
    @ApiOperation(value = "分页查询数据")
    @ResponseBody
    @SaCheckLogin
    public R getPage(@Validated SearchPageForm form){
        Page<Offer> page = new Page<>(form.getPageNum(), form.getPageSize());
        LambdaQueryWrapper<Offer> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtil.isEmpty(form.getName())){
            queryWrapper.like(Offer::getName,form.getName());
        }
        if (!StringUtil.isEmpty(form.getCardNumber())){
            queryWrapper.like(Offer::getCardNumber,form.getCardNumber());
        }
        if (!StringUtil.isEmpty(form.getExamineeNumber())){
            queryWrapper.like(Offer::getExamineeNumber,form.getExamineeNumber());
        }
        if (!StringUtil.isEmpty(form.getAcademicYear())){
            queryWrapper.like(Offer::getAcademicYear,form.getAcademicYear());
        }
        if (!StringUtil.isEmpty(form.getStudentType())){
            queryWrapper.like(Offer::getStudentType,form.getStudentType());
        }
        if (!StringUtil.isEmpty(form.getRegistAddress())){
            queryWrapper.like(Offer::getRegistAddress,form.getRegistAddress());
        }
        if (!StringUtil.isEmpty(form.getLicenceIssued())){
            queryWrapper.like(Offer::getLicenceIssued,form.getLicenceIssued());
        }

        queryWrapper.eq(Offer::getIsDelete,0);
        Page pageList = offerService.page(page, queryWrapper);
        return R.ok().put("page", pageList);
    }


    @OperLog(operModul = "通知书管理",operType = "添加",operDesc = "添加通知书")
    @ResponseBody
    @SaCheckPermission("offer:add")
    @PostMapping("/add")
    public R add(Offer offer){
        String cardNumber = offer.getCardNumber();
        String examineeNumber = offer.getExamineeNumber();
        String studentNumber = offer.getStudentNumber();

        QueryWrapper<Offer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_number",cardNumber);
        Offer card = offerService.getOne(queryWrapper);
        if (card != null){
            return R.error("身份证已存在！！！请重新输入您的身份证号！！");
        }

        queryWrapper.clear();
        queryWrapper.eq("examinee_number",examineeNumber);
        Offer examinee = offerService.getOne(queryWrapper);
        if (examinee != null){
            return R.error("考生号已存在！！！请重新输入您的考生号！！");
        }
        queryWrapper.clear();
        queryWrapper.eq("student_number",studentNumber);
        Offer stunumber = offerService.getOne(queryWrapper);
        if (stunumber != null ){
            return R.error("学号已经存在！！请重新输入您的学号！！");
        }

        offer.setCreateTime(new Date());
        offer.setCreateUser(userService.getUser().getUsername());
        offerService.save(offer);
        return R.ok();
    }


    @SaCheckPermission("offer:delete")
    @ResponseBody
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable int id){
        offerService.removeById(id);
        return R.ok();
    }

    @ResponseBody
    @GetMapping("/load/{id}")
    public R load(@PathVariable int id){
        Offer offer = offerService.getById(id);
        return R.ok().put("data",offer);

    }



    @SaCheckPermission("offer:update")
    @OperLog(operModul = "通知书管理",operType = "修改",operDesc = "修改通知书")
    @ResponseBody
    @PostMapping("/update")
    public R updadte(Offer offer){
//        设置修改时间，修改人
        offer.setUpdateTime(new Date());
        offer.setUpdateUser(userService.getUser().getUsername());
        boolean b = offerService.updateById(offer);
        if (b==false){
            return R.error();
        }else {
            return R.ok();
        }
    }



    @SaCheckPermission("offer:recycle")
    @GetMapping("/recycleIndex")
    @ApiOperation(value = "回收站页面")
    public String recycleIndex(Model model){
        model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+StpUtil.getLoginIdAsLong())); //用户权限
        return "offer/recycle";
    }


    @SaCheckPermission("offer:recycle")
    @PostMapping("/recycle")
    @ApiOperation(value = "根据id集合将数据放入回收站")
    @ResponseBody
    @OperLog(operModul = "通知书管理", operType = "放入回收站" ,operDesc = "将通知书放入回收站")
    public R recycle(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            List<Offer> offerList = new ArrayList<>();
            for(Long id : idList) {
                Offer offer = new Offer();
                offer.setId(id);
                offer.setIsDelete(1);
                offer.setUpdateTime(new Date());
                offer.setUpdateUser(userService.getUser().getUsername());
                offerList.add(offer);
            }
            if(offerList.size() > 0) {
                offerService.saveOrUpdateBatch(offerList);
            }
        }
        return R.ok("删除成功");
    }


    @SaCheckPermission("offer:recycle")
    @OperLog(operModul = "通知书管理",operType = "恢复通知书",operDesc = "还原回收站通知书")
    @PostMapping("/restore")
    @ApiOperation(value = "根据ids批量还原回收站的数据")
    @ResponseBody
    public R restore(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            List<Offer> offerList = new ArrayList<>();
            for(Long id : idList) {
                Offer offer = new Offer();
                offer.setId(id);
                offer.setUpdateTime(new Date());
                offer.setIsDelete(0);
                offerList.add(offer);
            }
            if(offerList.size() > 0) {
                offerService.saveOrUpdateBatch(offerList);
            }
        }
        return R.ok("还原成功");
    }

    @PostMapping("/getRecyclePage")
    @ApiOperation(value = "分页查询回收站数据")
    @ResponseBody
    public R getRecyclePage(@Validated SearchPageForm form){
        Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());
        LambdaQueryWrapper<Offer> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(Offer::getIsDelete, 1);

        Page pageList = offerService.page(roadPage, queryWrapper);
        return R.ok().put("page", pageList);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "根据id集合彻底删除数据")
    @SaCheckPermission("offer:delete")
    @ResponseBody
    @OperLog(operModul = "通知书管理", operType = "彻底删除" ,operDesc = "彻底删除通知书")
    public R delete(@Validated IdsForm form){
        List<Long> idList = form.idList();
        //检查是否存在不能修改的数据

        if(idList.size() > 0) {
            offerService.removeByIds(idList);
        }
        return R.ok("删除成功");
    }



    //    导入Excel
    @SaCheckLogin
    @PostMapping ("/excel")
    @ResponseBody
    @OperLog(operModul = "通知书上传Excel",operType = "批量上传",operDesc = "批量上传通知书")
    public R importExcel(@RequestPart MultipartFile file) throws Exception {

        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        List<List<Object>> bankListByExcel = excelUtil.getBankListByExcel(inputStream, filename);
        List<Object> objects = null;

        Offer offer = null;
        for (int i = 0; i < bankListByExcel.size(); i++) {
            objects = bankListByExcel.get(i);
            offer = new Offer();
            for (int j = 0; j < objects.size(); j++) {

                String o = (String)objects.get(j);
                if (j ==0){
                    offer.setName(o);
                }
                if (j == 1){
                    if (o.contains(".")){
                        String substring = o.substring(0, o.indexOf("."));
                        offer.setCardNumber(substring);
                    }
                    offer.setCardNumber(o);
                }
                if (j == 2){
                    if (o.contains(".")){
                        String substring = o.substring(0, o.indexOf("."));
                        offer.setExamineeNumber(substring);
                    }
                    offer.setExamineeNumber(o);
                }
                if (j == 3){
                    if (o.contains(".")){
                        String substring = o.substring(0, o.indexOf("."));
                        offer.setStudentNumber(substring);
                    }
                    offer.setStudentNumber(o);
                }
                if (j == 4){
                    offer.setEducation(o);
                }
                if (j == 5){
                    offer.setMajor(o);
                }

                if (j == 6){
                    offer.setPlace(o);
                }
                if (j == 7){
                    offer.setAcademicYear(o);
                }
                if (j == 8){

                    offer.setStudentType(o);
                }
                if (j == 9){
                    offer.setRegistTime(new SimpleDateFormat("yyyy-MM-dd").parse(o));
                }
                if (j == 10){
                    offer.setRegistAddress(o);
                }
                if (j == 11){
                    offer.setLicenceIssued(new SimpleDateFormat("yyyy-MM-dd").parse(o));
                }
                offer.setCreateTime(new Date());
                offer.setCreateUser(userService.getUser().getUsername());
            }
            offerService.save(offer);
        }

        return R.ok("批量导入成功！");
    }


    //    预览证书
    @SaCheckPermission("offer:view")
    @PostMapping("/preview/{id}")
    @OperLog(operModul = "通知书预览",operType = "通知书预览",operDesc = "通知书预览")
    public String preview(@PathVariable int id, HttpServletRequest request){
        System.out.println(id);
        Offer offer = offerService.getById(id);
        System.out.println(offer);
        String registTime = simpleDateFormat.format(offer.getRegistTime());
        String licenceIssued = simpleDateFormat.format(offer.getLicenceIssued());
        request.setAttribute("offer",offer);
        request.setAttribute("registTime",registTime);
        request.setAttribute("licenceIssued",licenceIssued);
        return "offer/offer";
    }


}
